<template>
    <el-container direction="vertical" class="family-control"> 
      <!-- 查询面板 -->
      <QueryPanel
        v-model="queryForm"
        :fields="queryFields"
        :actions="queryActions"
        @action="handleQueryAction"
      />
  
      <!-- 家庭列表 -->
      <DataTable
        :data="familyList"
        :loading="loading"
        :columns="tableColumns"
        :pagination="pagination"
        @page-change="handlePageChange"
        @size-change="handleSizeChange"
      >
      
      <!-- 创建时间显示 -->
        <template #created_at="{ row }">
          <span>
            {{ formatDateTime(row.created_at) }}
          </span>
        </template>
  
        <!-- 状态显示 -->
        <template #is_active="{ row }">
          <el-tag :type="row.is_active ? 'success' : 'danger'">
            {{ row.is_active ? '激活' : '未激活' }}
          </el-tag>
        </template>
        
        <!-- 成员显示 -->
        <template #members="{ row }">
          <el-space wrap :size="4">
            <el-tag 
              v-for="member in row.members" 
              :key="member.id"
              type="primary"
              size="small"
            >
              {{ member.username || member.nickname || '未知用户' }}
            </el-tag>
            <el-tag v-if="row.members.length === 0" type="info" size="small">
              暂无成员
            </el-tag>
          </el-space>
        </template>

        <!-- 成员数显示 -->
        <template #max_members="{ row }">
          <el-tag type="primary">
            {{ row.max_members || 0 }} 人
          </el-tag>
        </template>
  
        <!-- 操作按钮 -->
        <template #actions="{ row }">
          <!-- <el-button link type="primary" size="small" @click="handleViewFamily(row)">
            查看
          </el-button> -->
          <el-button link type="primary" size="small" @click="handleEditFamily(row)">
            编辑
          </el-button>
          <el-button link type="danger" size="small" @click="handleDeleteFamily(row)">
            删除
          </el-button>
        </template>
      </DataTable>
  
      <!-- 家庭表单对话框 -->
      <FormDialog
        v-model:visible="dialogVisible"
        :title="isEdit ? '编辑家庭' : '添加家庭'"
        :model-value="familyForm"
        :fields="familyFormFields"
        :rules="familyFormRules"
        :loading="saving"
        @submit="saveFamily"
        @close="resetFamilyForm"
      />
  
    </el-container>
  </template>
  
<script setup lang="ts">
  import { FamilyApi, FamilyInfo, FamilyQuery } from '@/api/family/family'
  import { reactive, ref, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import QueryPanel from '@/components/query/QueryPanel.vue' 
  import FormDialog from '@/components/page/FormDialog.vue'
  import { useUserStore } from '@/store'
  
  const userStore = useUserStore()
  
  // 分页配置
  const pagination = reactive({
    page: 1,
    pageSize: 10,
    total: 0
  })
  
  // 查询表单
  const queryForm = reactive<FamilyQuery>({
    page: 1,
    pageSize: 10,
  })
  
  // 查询字段配置
  const queryFields = [
    {
      prop: 'name',
      label: '家庭名称',
      type: 'input',
      placeholder: '请输入家庭名称'
    },
    {
      prop: 'is_active',
      label: '状态',
      type: 'select',
      placeholder: '请选择状态',
      options: [
        { label: '激活', value: true },
        { label: '未激活', value: false }
      ]
    },
    {
      prop: 'parent_id',
      label: '父家庭ID',
      type: 'input',
      placeholder: '请输入父家庭ID'
    }
  ]
  
  // 查询操作按钮
  const queryActions = [
    { name: 'search', label: '查询', type: 'primary' as const },
    { name: 'reset', label: '重置', type: '' as const },
    { name: 'add', label: '添加家庭', type: 'success' as const }
  ]
  
  // 表格列配置
  const tableColumns = [
    { prop: 'name', label: '家庭名称', width: 150 },
    { prop: 'description', label: '描述', minWidth: 200 },
    { prop: 'members', label: '家庭成员', slot: 'members', width: 100 },
    { prop: 'max_members', label: '最大成员数', slot: 'max_members', width: 100 },
    { prop: 'is_active', label: '状态', slot: 'is_active', width: 100 },
    { prop: 'created_at', label: '创建时间', slot: 'created_at', width: 200 },
  ]
  
  // 家庭表单字段配置
  const familyFormFields = [
    {
      prop: 'name',
      label: '家庭名称',
      type: 'input',
      placeholder: '请输入家庭名称',
      rules: { required: true, message: '请输入家庭名称', trigger: 'blur' }
    },
    {
      prop: 'description',
      label: '描述',
      type: 'textarea',
      placeholder: '请输入家庭描述',
      props: {
        rows: 3
      }
    },
    {
      prop: 'max_members',
      label: '最大成员数',
      type: 'number',
      placeholder: '请输入最大成员数',
      props: {
        min: 1,
        max: 100,
        controls: false
      },
      rules: { required: true, message: '请输入最大成员数', trigger: 'blur' }
    },
    {
      prop: 'order',
      label: '排序',
      type: 'number',
      placeholder: '请输入排序值',
      props: {
        min: 0,
        controls: false
      }
    },
    {
      prop: 'parent_id',
      label: '父家庭ID',
      type: 'number',
      placeholder: '请输入父家庭ID',
      props: {
        min: 0,
        controls: false
      }
    },
    {
      prop: 'is_active',
      label: '是否激活',
      type: 'switch',
      props: {
        activetext: '激活',
        inactivetext: '未激活'
      }
    }
  ]
  
  // 家庭表单验证规则
  const familyFormRules = {}
  
  // 数据状态
  const loading = ref(false)
  const saving = ref(false)
  const dialogVisible = ref(false)
  const isEdit = ref(false)
  const currentFamilyId = ref<number | null>(null)
  const familyList = ref<FamilyInfo[]>([])
  
  // 家庭表单
  const familyForm = reactive<Partial<FamilyInfo>>({
    id: null,
    name: '',
    description: '',
    max_members: 20,
    order: 0,
    parent_id: 0,
    is_active: true,
    created_by: 0
  })
  
  // 保存家庭
  const saveFamily = async () => {
    try {
      saving.value = true
      if (isEdit.value) {
        // 编辑模式
        if (currentFamilyId.value) {
          await FamilyApi.updateFamily(currentFamilyId.value, familyForm)
          ElMessage.success('更新成功')
        }
      } else {
        // 新增模式
        await FamilyApi.createFamily(familyForm)
        ElMessage.success('新增成功')
      }
      dialogVisible.value = false
      loadFamilies() // 刷新列表
    } catch (error) {
      ElMessage.error(isEdit.value ? '更新失败' : '新增失败')
    } finally {
      saving.value = false
    }
  }
  
  // 重置家庭表单
  const resetFamilyForm = () => {
    Object.assign(familyForm, {
      id: null,
      name: '',
      description: '',
      max_members: 20,
      order: 0,
      parent_id: 0,
      is_active: true,
      created_by: userStore.userInfo.id
    })
  }
  
  // 添加家庭
  const handleAddFamily = () => {
    isEdit.value = false
    currentFamilyId.value = null
    resetFamilyForm()
    dialogVisible.value = true
  }
  
  // 查询方法
  const loadFamilies = async () => {
    try {
      loading.value = true
      const response = await FamilyApi.getFamilies(queryForm)
      
      familyList.value = response.data
      pagination.total = response.total
      pagination.pageSize = response.page_size
    } catch (error) {
      ElMessage.error('获取家庭列表失败')
    } finally {
      loading.value = false
    }
  }
  
  const handlePageChange = (page: number) => {
    queryForm.page = page
    loadFamilies()
  }
  
  const handleSizeChange = (size: number) => {
    queryForm.pageSize = size
    queryForm.page = 1
    loadFamilies()
  }
  
  // 时间格式化函数
  const formatDateTime = (dateString: string): string => {
    if (!dateString) return '';
    try {
      const formatDate = new Date(dateString).toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      }).replace(/\//g, '-');
      return formatDate;
    } catch (error) {
      return dateString;
    }
  }
  
  const handleQueryAction = (action: string) => {
    switch (action) {
      case 'search':
        queryForm.page = 1
        loadFamilies()
        break
      case 'reset':
        Object.assign(queryForm, {
          name: '',
          is_active: undefined,
          parent_id: undefined,
          page: 1,
          pageSize: 10
        })
        loadFamilies()
        break
      case 'add':
        handleAddFamily()
        break
    }
  }
  
  const handleViewFamily = (family: FamilyInfo) => {
    // 跳转到家庭详情页
    // 暂时没写 。
    console.log('查看家庭详情:', family.id)
  }
  
  const handleEditFamily = (family: FamilyInfo) => {
    isEdit.value = true
    currentFamilyId.value = family.id
    Object.assign(familyForm, {
      id: family.id,
      name: family.name,
      description: family.description,
      max_members: family.max_members,
      order: family.order,
      parent_id: family.parent_id,
      is_active: family.is_active,
      created_by: family.created_by
    })
    dialogVisible.value = true
  }
  
  const handleDeleteFamily = async (family: FamilyInfo) => {
    try {
      await ElMessageBox.confirm(`确定要删除家庭"${family.name}"吗？`, '提示', {
        type: 'warning'
      })
      await FamilyApi.deleteFamily(family.id)
      ElMessage.success('删除成功')
      loadFamilies()
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除失败')
      }
    }
  }
  
  onMounted(() => {
    loadFamilies()
  })
  </script>
  
  <style scoped>
  .family-control {
    padding: 20px;
  }
  </style>